package com.lxb.uploadwithprogress.http;

import java.io.File;





import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
//import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

//import com.example.android.bitmapfun.util.AsyncTask;
//import com.speed.im.utils.AsyncTask;
//import com.speed.im.utils.AsyncTask.Status;
import com.lxb.uploadwithprogress.http.CustomMultipartEntity.ProgressListener;
//import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.spice.im.utils.AsyncTask;

public class HttpMultipartPost extends AsyncTask<String, Integer, String> {

//	private Context context;
//	private String filePath;
//	private ProgressDialog pd;
	private long totalSize;
	
//	private String fromAccount;
//	private String toAccount;
	private Handler handler;
	private int sendresult = 0;
	public int getSendresult(){
		return this.sendresult;
	}

//	private AlertDialog.Builder builder;
	public HttpMultipartPost(Handler handler) {
//		this.context = context;
//		this.filePath = filePath;
//		this.fromAccount = fromAccount;
//		this.toAccount = toAccount;
		this.handler = handler;
	}

	@Override
	protected void onPreExecute() {
//		builder = new AlertDialog.Builder(context);
//		pd = new ProgressDialog(context);
//		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//		pd.setMessage("Uploading Picture...");
//		pd.setCancelable(false);
//		pd.show();
	}

	@Override
	protected String doInBackground(String... params) {
		
		Log.e("===============20130904=================", "params[0]="+params[0]+";params[1]="+params[1]+";params[2]="+params[2]);
		
		String serverResponse = null;
		
		HttpParams params2 = new BasicHttpParams(); 
		HttpConnectionParams.setConnectionTimeout(params2, 10000); //设置连接超时
		HttpConnectionParams.setSoTimeout(params2, 10000); //设置请求超时
		
		

		HttpClient httpClient = new DefaultHttpClient(params2);
		HttpContext httpContext = new BasicHttpContext();
//		HttpPost httpPost = new HttpPost("http://10.0.2.2:8080/uploads/FileUploadServlet");
//		HttpPost httpPost = new HttpPost(XmppConnectionAdapter.downloadPrefix+"uploads/FileUploadServlet");
		HttpPost httpPost = new HttpPost("uploads/FileUploadServlet");
		if(params[5]!=null)
			httpPost = new HttpPost(params[5]);
		else
//		httpPost = new HttpPost(XmppConnectionAdapter.uploadHost);
			httpPost = new HttpPost("uploads/FileUploadServlet");
//		httpPost = new HttpPost("http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer");

		try {
			CustomMultipartEntity multipartContent = new CustomMultipartEntity(
					new ProgressListener() {
						@Override
						public void transferred(long num) {
							publishProgress((int) ((num / (float) totalSize) * 100));
						}
					});

			// We use FileBody to transfer an image
			multipartContent.addPart("data", new FileBody(new File(
					params[0])));//filePath
			//20130712 add params while filetransfer start
//			multipartContent.addPart("key", new StringBody("value"));
			multipartContent.addPart("fromAccount", new StringBody(params[1]));//this.fromAccount
			multipartContent.addPart("toAccount", new StringBody(params[2]));//this.toAccount
			multipartContent.addPart("sendType", new StringBody(params[3]));//this.toAccount
			multipartContent.addPart("sendSize", new StringBody(params[4]));//this.toAccount
			
			
			//20130712 add params while filetransfer end
			totalSize = multipartContent.getContentLength();

			// Send it
			httpPost.setEntity(multipartContent);
			
			HttpResponse response = httpClient.execute(httpPost, httpContext);
			Log.e("===============20130904=================", "++++++++++++++progressbar start httpMultipartPost execute+++++++++++++");
			
			serverResponse = EntityUtils.toString(response.getEntity());
			Log.e("===============20130904=================", "++++++++++++++progressbar start httpMultipartPost serverResponse+++++++++++++");
		} catch (Exception e) {
			e.printStackTrace();
            // 处理超时 covers: 
            //        ClientProtocolException 
            //        ConnectTimeoutException 
            //        ConnectionPoolTimeoutException 
            //        SocketTimeoutException 
////			AlertDialog.Builder builder = new AlertDialog.Builder(context);
//			builder.setTitle("警告");
//			builder.setPositiveButton("确定",null);
//			builder.setIcon(android.R.drawable.ic_dialog_info);
//			builder.setMessage("错误:"+e.getMessage());
////			builder.show(); 
//			handler2.sendEmptyMessage(1);
			
			this.handler.sendEmptyMessage(4);
		}

		return serverResponse;
	}

//	private Handler handler2 = new Handler() {
//		
//		public void handleMessage(android.os.Message msg) {
//			switch (msg.what) {
//				case 1:
//					builder.show(); 
//					break;
//				default:
//					break;
//			}
//		}
//	};
	@Override
	protected void onProgressUpdate(Integer... progress) {
//		pd.setProgress((int) (progress[0]));
		android.os.Message message = this.handler.obtainMessage();
		message.arg2 = (int) totalSize;//20140602 
		message.arg1 = (int) (progress[0]);
		message.what = 3;
//							message.sendToTarget();
		this.handler.sendMessage(message);
	}

	@Override
	protected void onPostExecute(String result) {
//		System.out.println("result: " + result);
		sendresult = 1;
//		pd.dismiss();
//		this.handler.sendEmptyMessage(6);
		this.handler.sendEmptyMessage(4);
	}

	@Override
	protected void onCancelled() {
		System.out.println("cancle");
	}

}
